﻿using RpcHelper;
using RpcModel;
using RpcSync.Collect.Model;
using RpcSync.Model;

namespace RpcSync.Service.ConfigService
{
    internal static class LinqHelper
    {
        public static string GetConfigVal(this SysConfigItem config, string name, MsgSource source)
        {
            ConfigItem[] configs = config.Items.FindAll(a => a.CheckIsMatching(name, source));
            if (configs.Length > 0)
            {
                return configs.OrderByDescending(a => a.Weight).Select(a => a.Value).FirstOrDefault();
            }
            return null;
        }
        public static SysConfigData[] Filters(this SysConfigItem config, MsgSource source)
        {
            ConfigItem[] configs = config.Items.FindAll(a => a.CheckIsMatching(source));
            if (configs.Length > 0)
            {
                return configs.OrderByDescending(a => a.Weight).Select(a => new SysConfigData
                {
                    Name = a.Name,
                    IsJson = a.ValueType ==  SysConfigValueType.JSON,
                    Value = a.Value,
                    Prower = a.Prower
                }).Distinct().ToArray();
            }
            return null;
        }
        public static bool CheckIsMatching(this ConfigItem config, string name, MsgSource source)
        {
            if (name != config.Name)
            {
                return false;
            }
            return config.CheckIsMatching(source);
        }
        public static bool CheckIsMatching(this ConfigItem item, MsgSource source)
        {
            if (item.IsPublic)
            {
                return true;
            }
            else if (item.RpcMerId != 0 && item.RpcMerId != source.RpcMerId)
            {
                return false;
            }
            else if (item.ServerId != 0 && item.ServerId != source.ServerId)
            {
                return false;
            }
            return true;
        }
    }
}
